﻿/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using IAPRepo_WebRole.Models;
using System.IO;
using System.Diagnostics;

namespace IAPRepo_WebRole.Controllers
{
    public class RequireBasicAuthentication : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var authenticated = false;
            var req = filterContext.HttpContext.Request;

            if (!String.IsNullOrEmpty(req.Headers["Authorization"]))
            {
                var cred =
                    System.Text.ASCIIEncoding.ASCII
                    .GetString(Convert.FromBase64String(
                    req.Headers["Authorization"].Substring(6)))
                    .Split(':');

                // Username and password
                authenticated = cred[0] == "admin" && cred[1] == "password";
            }

            if (!authenticated)
            {
                var res = filterContext.HttpContext.Response;
                res.StatusCode = 401;
                res.AddHeader("WWW-Authenticate", "Basic realm=\"IAP Repo\"");
                res.End();
            }
        }
    }

    public class HomeController : BaseCloudStorageController
    {
        [RequireBasicAuthentication]
        public ActionResult Index()
        {
            var query = tableContext.CreateQuery<IAPProduct>(IAPProduct.TABLE_NAME)
                .Where(p => p.PartitionKey == IAPProduct.PARTITION_KEY).AsTableServiceQuery();

            return View(query);
        }

        [RequireBasicAuthentication]
        [HttpPost]
        public ActionResult Add(IAPProduct product)
        {
            Debug.WriteLine("Add() called with input " + product);

            tableContext.AddObject(IAPProduct.TABLE_NAME, product);
            tableContext.SaveChangesWithRetries();
            
            return RedirectToAction("Index");
        }

        [RequireBasicAuthentication]
        public ActionResult Delete(string rowKey)
        {
            Debug.WriteLine("Delete() called with rowKey " + rowKey);

            var product = getProduct(rowKey);

            // Delete references downloadable blob
            if (product.DownloadableBlobName != null)
            {
                blobContainer.GetBlobReference(product.DownloadableBlobName).DeleteIfExists();
            }

            // Delete referenced image blob
            if (product.ImageBlobName != null)
            {
                blobContainer.GetBlobReference(product.ImageBlobName).DeleteIfExists();
            }

            tableContext.DeleteObject(product);
            tableContext.SaveChangesWithRetries();

            return RedirectToAction("Index");
        }

        [RequireBasicAuthentication]
        private Uri UploadBlob(HttpPostedFileBase file, string blobName)
        {
            if (file == null || file.ContentLength == 0)
            {
                Debug.WriteLine("UploadBlob: file null or has no size");
                return null;
            }

            Debug.WriteLine("Uploading as " + blobName);
            CloudBlob blob = blobContainer.GetBlobReference(blobName);            
            blob.UploadFromStream(file.InputStream);
            Debug.WriteLine("Uploaded blob length " + blob.Properties.Length + ", Uri " + blob.Uri);

            return blob.Uri;
        }

        [RequireBasicAuthentication]
        [HttpPost]
        public ActionResult AddFile(string rowKey, HttpPostedFileBase file)
        {
            // If successful, save a reference in the corresponding product
            var blobName = rowKey + "_binary" + Path.GetExtension(file.FileName);
            var blobUri = UploadBlob(file, blobName);

            Debug.WriteLine("AddFile blobUri: " + blobUri.ToString());
            if (blobUri != null)
            {
                var product = getProduct(rowKey);
                product.DownloadableBlobName = blobName;
                product.DownloadableUri = blobUri.ToString();
                tableContext.UpdateObject(product);
                tableContext.SaveChangesWithRetries();
            }
            
            return RedirectToAction("Index");
        }

        [RequireBasicAuthentication]
        [HttpPost]
        public ActionResult AddImage(string rowKey, HttpPostedFileBase file)
        {
            // If successful, save a reference in the corresponding product
            var blobName = rowKey + "_image" + Path.GetExtension(file.FileName);            
            var blobUri = UploadBlob(file, blobName);

            Debug.WriteLine("AddImage blobUri: " + blobUri.ToString());
            if (blobUri != null)
            {
                var product = getProduct(rowKey); 
                product.ImageBlobName = blobName;
                product.ImageUri = blobUri.ToString();
                tableContext.UpdateObject(product);
                tableContext.SaveChangesWithRetries();
            }
            
            return RedirectToAction("Index");
        }
    }
}
